<template>
  <div class="ref">

    <form action="/" >
      <van-search placeholder="" v-model="sval" show-action @search="onSearch" @cancel="onCancel" style="position:fixed;top:0vh;left:0vw;width:100vw;z-index:1"/>
    </form>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" style="margin-top:8vh;margin-bottom:8vh;" >
      <van-list v-model="loading" :finished="finished" finished-text="已加载全部数据" @load="onLoad">
        <van-cell v-for="item in list" :key="item.ids">
          <template #title>
            名称:<span>{{ item.sname }}</span><br>
            <span style="font-size: 12px;color: #969799;">编码：{{item.scode}}</span><br>
            <span style="font-size: 12px;color: #969799;">规格：{{item.sspec}}</span><br>
            <span style="font-size: 12px;color: #969799;">单位：{{item.measure}}</span><br>
            <span style="font-size: 12px;color: #969799;">包装：{{item.bz}}</span><br>
            <span style="font-size: 12px;color: #969799;">开票单位：{{item.kpdw}}</span><br>
            <span style="font-size: 12px;color: #969799;">协议开票价：{{item.xykpj}}</span><br>
          </template>
          <template #default>
            <div style="display:inline-block">件数<van-stepper @blur="bzjs(item, 'js', 'input')" @plus="bzjs(item, 'js','plus')" @minus="bzjs(item, 'js','min')" v-model="item.js" theme="round" min="0" button-size="18" input-width="40"/></div><br/>
            <div style="display:inline-block">数量<van-stepper @blur="bzjs(item, 'sl', 'input')" @plus="bzjs(item, 'sl','plus')" @minus="bzjs(item, 'sl','min')" v-model="item.sl" theme="round" min="0" button-size="18" input-width="40"/></div>
          </template>
        </van-cell>
      </van-list>
    </van-pull-refresh>
    <van-tabbar v-model="active">
      <van-tabbar-item @click="addcard()">
        <span>加入购物车</span>
        <template #icon="props">
          <van-icon name="plus" size="20"/>
        </template>
      </van-tabbar-item>
      <van-tabbar-item @click="showcard()">
        <span>查看购物车</span>
        <template #icon="props">
          <van-icon name="shopping-cart-o" size="20" :badge="cardlist.length"/>
        </template>
      </van-tabbar-item>
      <van-tabbar-item @click="openSDNew()">
        <span>下一步</span>
        <template #icon="props">
          <van-icon name="arrow" size="20"/>
        </template>
      </van-tabbar-item>
    </van-tabbar>
    <van-popup v-model="cardshow" position="right" style="width:90vw;height:100vh;overflow: hidden" @click-overlay="closeCard">
      <div style="height: 90%;overflow: auto">
      <van-cell v-for="item in cardlist" :key="item.ids" >
        <template #title>
          名称:<span>{{ item.sname }}</span><br>
          <span style="font-size: 12px;color: #969799;">编码：{{item.scode}}</span><br>
          <span style="font-size: 12px;color: #969799;">规格：{{item.sspec}}</span><br>
          <span style="font-size: 12px;color: #969799;">单位：{{item.measure}}</span><br>
          <span style="font-size: 12px;color: #969799;">包装：{{item.bz}}</span><br>
        </template>
        <template #default>
          <div style="display:inline-block">件数<van-stepper @blur="bzjs4Card(item, 'js', 'input')" @plus="bzjs4Card(item, 'js','plus')" @minus="bzjs4Card(item, 'js','min')" v-model="item.js" theme="round" min="0" button-size="18" input-width="40"/></div><br/>
          <div style="display:inline-block;margin-bottom:3vh">数量<van-stepper @blur="bzjs4Card(item, 'sl', 'input')" @plus="bzjs4Card(item, 'sl','plus')" @minus="bzjs4Card(item, 'sl','min')" v-model="item.sl" theme="round" min="0" button-size="18" input-width="40"/></div><br>
          <van-icon @click="del(item)" size="20" name="cross" />
        </template>
      </van-cell>
      </div>
      <van-tabbar v-model="buttonactive"  >
        <van-tabbar-item @click="closeCard">关闭</van-tabbar-item>
        <van-tabbar-item @click="clearcard">清空购物车</van-tabbar-item>
      </van-tabbar>

    </van-popup>
  </div>
</template>

<script>
import Vue from 'vue'
import { Search, List, Cell, PullRefresh, Toast, Tabbar, TabbarItem, Popup, Stepper, Icon } from 'vant'
import qs from 'qs'
import { keepNDecimalFull } from '../assets/js/tool'
Vue.use(Search).use(List).use(Cell).use(PullRefresh).use(Toast).use(Tabbar).use(TabbarItem).use(Popup).use(Stepper).use(Icon)
export default {
  name: 'hzxydlproduct',
  data () {
    return {
      sval: '',
      list: [],
      loading: false,
      finished: false,
      isLoading: false,
      startline: 1,
      pagecount: 15,
      active: 0,
      cardlist: [],
      cardshow: false,
      buttonactive: 0,
      dlkh: '',
      account3id: this.$route.params.account3id
    }
  },
  methods: {
    onLoad () {
      let data = {
        'ref_object': this.$route.params.bo,
        'ref_inview': 'sname:in:',
        'view_id': this.$route.params.viewid,
        'ref_classname': this.$route.params.classname,
        'ref_params': this.$route.params.params,
        'account3id': this.$route.params.account3id,
        'where1': this.sval,
        'startline': this.startline
      }
      this.axios({
        method: 'post',
        url: '/api/hzxydl.getproduct.do',
        data: qs.stringify(data)
      }).then(res => {
        // //console.log(res.data)
        // //console.log('account3id:' + this.account3id)
        // for (var i = 0; i < localStorage.length; i++) {
        //   var key = localStorage.key(i) // 获取本地存储的Key
        //   //console.log(key)
        //   //console.log(localStorage.getItem(key))// 所有value
        //   //console.log('---------------------------------')
        // }

        if (typeof (res.data.flag) !== 'undefined' && res.data.flag === '1') {
          Toast('系统异常 请联系管理员', { duration: 10000 })
          this.isloading = false
          this.loading = false
          this.finished = true
          return
        }
        let rsdata = res.data

        for (let i = 0; i < rsdata.length; i++) {
          this.list.push(rsdata[i])
        }
        this.handleReadFromLocalStorage()

        for (let i = 0; i < rsdata.length; i++) {
          for (let index in this.cardlist) {
            if (this.cardlist[index].ids === rsdata[i].ids) {
              rsdata[i].js = this.cardlist[index].js
              rsdata[i].sl = this.cardlist[index].sl
              break
            }
          }
        }
        if (rsdata == null || rsdata.length === 0 || rsdata.length < this.pagecount) {
          this.loading = false
          this.finished = true
        } else {
          this.startline = this.startline + rsdata.length
          this.loading = false
        }
      }).catch(res => {
        this.reserror(res)
      })
    },
    onRefresh () {
      this.list = []
      this.startline = 1
      this.isLoading = false
      this.loading = true
      this.finished = false
      this.onLoad()
    },
    onSearch () {
      this.list = []
      this.startline = 1
      this.onLoad()
    },
    onCancel () {
      this.sval = ''
      this.list = []
      this.startline = 1
      this.onLoad()
    },
    addcard () {
      let alllist = this.list
      for (let i = 0; i < alllist.length; i++) {
        if (alllist[i].js > 0 || alllist[i].sl > 0) {
          let flag = true
          for (let index in this.cardlist) {
            if (this.cardlist[index].ids === alllist[i].ids) {
              this.cardlist[index].js = alllist[i].js
              this.cardlist[index].sl = alllist[i].sl
              flag = false
              break
            }
          }
          if (flag) {
            this.cardlist.push(alllist[i])
          }
        }
      }
      Toast('加入成功')
      //console.log(this.cardlist)
      this.handleAddToLocalStorage()
    },
    showcard () {
      this.cardshow = true
    },
    openSDNew () {
      let headid = ''
      let bodyid = ''
      let js = ''
      let sl = ''
      if (this.cardlist.length === 0) {
        Toast('未选中产品')
        return
      }
      Toast('正在统计购物车')
      for (let i = 0; i < this.cardlist.length; i++) {
        headid += this.cardlist[i].id + ';'
        bodyid += this.cardlist[i].ids + ';'
        js += this.cardlist[i].js + ';'
        sl += this.cardlist[i].sl + ';'
      }
      Toast('跳转中')
      this.$router.push({ path: '/sdnew', query: { account3id: this.$route.params.account3id, idobject: 'sorder', refobject: 'hzxydl', relopeid: '15613695695551081202245222999830', headid: headid, bodyid: bodyid, js: js, sl: sl, ksxd: '1', date: new Date().getTime() } })
    },
    bzjs (item, type, flag) {
      if (type === 'js') {
        if (flag === 'plus') {
          item.js = item.js + 1
        } else if (flag === 'min') {
          item.js = item.js - 1
        }
        item.sl = keepNDecimalFull(item.js * item.bz, 2)
      } else if (type === 'sl') {
        if (flag === 'plus') {
          item.sl = item.sl + 1
        } else if (flag === 'min') {
          item.sl = item.sl - 1
        }
        item.js = keepNDecimalFull(item.sl / item.bz, 6)
      }
      //console.log(item)
    },
    // 监听购物车的事件,以同时更新localstorage的值,原按钮逻辑不变
    bzjs4Card (item, type, flag) {
      this.bzjs(item, type, flag)
      let cs = this.cardlist
      //console.log('cs:' + cs)
      let arr = JSON.parse(localStorage.getItem(this.account3id))
      for (let i = 0; i < cs.length; i++) {
        if (cs[i].ids === item.ids) {
          for (let j = 0; j < arr.length; j++) {
            if (arr[j].ids === item.ids) {
              arr[j].sl = item.sl
              arr[j].js = item.js
              break
            }
          }
          localStorage.setItem(this.account3id, JSON.stringify(arr))
          break
        }
      }
      // let valJson = JSON.parse(localStorage.getItem(this.dlkh))
      // valJson.sl = item.sl
      // valJson.js = item.js
      // localStorage.setItem(this.account3id, JSON.stringify(valJson))
    },
    del (item) {
      let cardlist = this.cardlist
      let arr = JSON.parse(localStorage.getItem(this.account3id))
      for (let i = 0; i < cardlist.length; i++) {
        if (cardlist[i].ids === item.ids) {
          // 同时删除localStorage里对应的key
          // localStorage.removeItem(cardlist[i].ids)
          for (let j = 0; j < arr.length; j++) {
            if (arr[j].ids === item.ids) {
              arr.splice(j, 1)
              break
            }
          }
          localStorage.setItem(this.account3id, JSON.stringify(arr))
          item.sl = 0
          item.js = 0
          cardlist.splice(i, 1)
        }
      }
    },
    clearcard () {
      this.handleClearLocalStorage()
      let list = this.list
      for (let i = 0; i < list.length; i++) {
        list[i].sl = 0
        list[i].js = 0
      }
      this.cardlist = []
    },
    /**
     *处理 从LocalStorage读取
     */
    handleReadFromLocalStorage () {
      let ls = this.list
      if (ls == null || ls.length <= 0) { return }
      this.cardlist.length = 0
      let arr = JSON.parse(localStorage.getItem(this.account3id))
      if (arr) {
        for (let i = 0; i < arr.length; i++) {
          this.cardlist.push(arr[i])
        }
        //console.log('handleReadFromLocalStorage: ' + this.cardlist)
      }
    },
    /**
     *处理 添加到LocalStorage
     */
    handleAddToLocalStorage () {
      let cs = this.cardlist
      //console.log('cardlist:  ' + cs)
      if (cs == null || cs.length <= 0) { return }
      let jss = []
      for (let i = 0; i < cs.length; i++) {
        // 以ids为key,保存json字符串
        jss.push(cs[i])
      }
      localStorage.setItem(this.account3id, JSON.stringify(jss))
      //console.log('handleAddToLocalStorage: done')
    },

    handleClearLocalStorage () {
      let cs = this.cardlist
      if (cs == null || cs.length <= 0) { return }
      localStorage.removeItem(this.account3id)

      //console.log('handleClearLocalStorage: done')
    },
    closeCard () {
      this.cardshow = false
    }
  }
}

</script>

<style>
.fieldgroup_title {
    text-align: left;
    margin: 0px;
    padding: 35px 15px 15px;
    color: rgba(69,90,100,0.6);
    font-weight: normal;
    font-size: 14px;
}
</style>
